package io.github.maojian.str;

import org.junit.Test;

import java.util.Arrays;

public class Q1417 {

    /**
     * 暴力破解
     */
    public String reformat(String s) {
        int length = s.length();
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        StringBuilder ans = new StringBuilder();
        int mid = length / 2;

        if (length % 2 == 0) {
            if (Character.isLetter(chars[mid]) && Character.isDigit(chars[mid - 1])) {
                for (int i = 0; i < mid; i++) {
                    ans.append(chars[i]);
                    ans.append(chars[mid + i]);
                }
            } else {
                return "";
            }
        } else {
            if (Character.isLetter(chars[mid + 1]) && Character.isDigit(chars[mid - 1])) {
                for (int i = 0; i < mid; i++) {
                    ans.append(chars[i]);
                    ans.append(chars[mid + i + 1]);
                }
                if (Character.isLetter(chars[mid])) {
                    ans.insert(0, chars[mid]);
                } else {
                    ans.append(chars[mid]);
                }
            } else {
                return "";
            }
        }
        return ans.toString();
    }

    public String reformat01(String s) {
        int length = s.length();
        int digitCount = 0;
        for (int i = 0; i < length; i++) {
            if (Character.isDigit(s.charAt(i))) {
                digitCount++;
            }
        }
        int letterCount = length - digitCount;
        // 若数字个数与字母个数相差大于1无法按要求格式化，返回""
        if (Math.abs(digitCount - letterCount) > 1) {
            return "";
        }
        // 判断数字多还是字母多
        boolean isDigitMore = digitCount > letterCount;

        char[] chars = s.toCharArray();
        // 利用双指针调整字符顺序-偶数位置放多的，奇数位置放置少的
        for (int i = 0, j = 1; i < length; i += 2) {
            if (Character.isDigit(chars[i]) != isDigitMore) {
                while (Character.isDigit(chars[j]) != isDigitMore) {
                    j += 2;
                }
                char c = chars[i];
                chars[i] = chars[j];
                chars[j] = c;
            }
        }
        return new String(chars);
    }

    @Test
    public void test() {
        String s = "a0b1c2";
        System.out.println(reformat01(s));
    }
}
